﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BrnMall.Manager.Domain.Restaurant;
using BrnMall.Manager.Manager.Restaurant;
using BrnMall.Services;
using PetaPoco;
using QIDong.WeApp.Models;
using WeiTap.Restful;

namespace QIDong.WeApp.Controllers
{
    /// <summary>
    /// 餐饮相关功能
    /// </summary>
    public class RestaurantController : WebApi
    {
        private static readonly object _lineLock = new object();

        #region 排队

        /// <summary>
        /// 获取店铺的排队项列表
        /// </summary>
        /// <param name="storeId">店铺ID</param>
        /// <returns></returns>
        public IList<LineItemModel> GetStoreLineItems(int storeId)
        {
            var itemList = LineManager.GetStoreLineItems(storeId);
            var result = itemList.Select(t => new LineItemModel
            {
                CurrNumber = t.CurrNumber,
                DisplayOrder = t.DisplayOrder,
                Name = t.Name,
                Id = t.Id,
                NextNumber = t.NextNumber,
                Remark = t.Remark,
                StartCode = t.StartCode,
                StoreId = t.StoreId,
                PendingCount = LineManager.GetLineQueueCount(0, t.Id, 0)
            }).ToList();
            return result;
        }

        /// <summary>
        /// 获取排队队列数据
        /// </summary>
        /// <param name="storeid">店铺编号</param>
        /// <param name="lineId">排队项ID</param>
        /// <param name="queueState">状态-1所有状态，0排队中，1正叫号，2已就餐，3已过号</param>
        /// <param name="pageNumber">当前页面</param>
        /// <param name="pageSize">每页多少条</param>
        /// <returns></returns>
        public Page<LineQueueModel> GetLineQueue(int storeid, int lineId = 0, int queueState = -1, long pageNumber = 1, long pageSize = 15)
        {
            var queueList = LineManager.GetLineQueuePage(lineId, storeid, queueState, pageSize, pageNumber);
            var result = new Page<LineQueueModel>
            {
                CurrentPage = queueList.CurrentPage,
                Items = queueList.Items.Select(t => new LineQueueModel
                {
                    Id = t.Id,
                    LineItem = LineManager.GetLineItem(t.LineId),
                    LineNumber = t.LineNumber,
                    QueueState = t.QueueState,
                    StoreId = t.StoreId,
                    User = Users.GetPartUserById(t.Uid),
                    CreateTime = t.CreateTime,
                    StartCode = t.StartCode,
                    VoiceSrc = GetLineCodeVoiceSrc(t.StartCode, t.LineNumber)
                }).ToList(),
                ItemsPerPage = queueList.ItemsPerPage,
                TotalItems = queueList.TotalItems,
                TotalPages = queueList.TotalPages
            };
            return result;

        }

        /// <summary>
        /// 客户取号
        /// </summary>
        /// <param name="lineId">排队项ID</param>
        /// <param name="uid">用户ID</param>
        /// <returns></returns>
        public LineQueueModel FetchNumber(int lineId, int uid)
        {
            var lineItem = LineManager.GetLineItem(lineId);
            var inLine = LineManager.CheckInLineQueue(lineItem.StoreId, uid);
            if (inLine)
            {
                throw new ApiException("当前正在排队中");
            }
            lock (_lineLock)
            {
                
                var newQueue = new LineQueue
                {
                    LineId = lineId,
                    LineNumber = lineItem.NextNumber,
                    QueueState = 0,
                    StoreId = lineItem.StoreId,
                    Uid = uid,
                    CreateTime = DateTime.Now,
                    StartCode = lineItem.StartCode
                };
                LineManager.AddLineQueue(newQueue);
                var result = new LineQueueModel
                {
                    Id = newQueue.Id,
                    LineItem = LineManager.GetLineItem(newQueue.LineId),
                    LineNumber = newQueue.LineNumber,
                    QueueState = newQueue.QueueState,
                    StoreId = newQueue.StoreId,
                    User = Users.GetPartUserById(newQueue.Uid),
                    BeforeCount = LineManager.GetLineQueueCount(newQueue.Id, newQueue.LineId, 0),
                    CreateTime = newQueue.CreateTime,
                    StartCode = newQueue.StartCode,
                    VoiceSrc = GetLineCodeVoiceSrc(newQueue.StartCode,newQueue.LineNumber)
                };
                return result;

            }
        }
        /// <summary>
        /// 判断当前用户是否正在排队
        /// </summary>
        /// <param name="storeId">店铺ID</param>
        /// <param name="uid">用户ID</param>
        /// <returns></returns>
        public bool CheckInlineQueue(int storeId, int uid)
        {
            return LineManager.CheckInLineQueue(storeId, uid);
        }
        /// <summary>
        /// 获取客户已取号码
        /// </summary>
        /// <param name="storeId">店铺ID</param>
        /// <param name="uid">用户ID</param>
        /// <returns></returns>
        public LineQueueModel GetNumber(int storeId, int uid)
        {
            var lineQueue = LineManager.GetLineQueueByUid(storeId, uid);
            if(lineQueue==null)
                throw new Exception("未在排队状态中");
            var result = new LineQueueModel
            {
                Id = lineQueue.Id,
                LineItem = LineManager.GetLineItem(lineQueue.LineId),
                LineNumber = lineQueue.LineNumber,
                QueueState = lineQueue.QueueState,
                StoreId = lineQueue.StoreId,
                User = Users.GetPartUserById(lineQueue.Uid),
                BeforeCount = LineManager.GetLineQueueCount(lineQueue.Id, lineQueue.LineId, 0),
                CreateTime = lineQueue.CreateTime,
                StartCode = lineQueue.StartCode,
                VoiceSrc = GetLineCodeVoiceSrc(lineQueue.StartCode,lineQueue.LineNumber)
            };
            return result;


        }
        /// <summary>
        /// 更新队列的状态
        /// </summary>
        /// <param name="id">队列排序ID</param>
        /// <param name="queueState">1正叫号，2已就餐，3已过号</param>
        public void UpdateLineQueueState(long id, int queueState)
        {
            LineManager.UpdateLineQueueState(id,queueState);
        }
        /// <summary>
        /// 客户取消排队
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool CancelQueue(int storeId, int uid)
        {
            LineManager.DeleteLineQueue(storeId,uid);
            return true;
        }
        #endregion

        #region 餐位
        /// <summary>
        /// 获取店铺餐位设置
        /// </summary>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public DiningTableListModel GetStoreDiningTables(int storeId)
        {
            var list = new DiningTableListModel
            {
                DiningTables = DiningTableManager.GetStoreDiningTables(storeId).Select(t => new DiningTableViewModel
                {
                    DiningState = t.DiningState,
                    Id = t.Id,
                    StoreId = t.StoreId,
                    TableNumber = t.TableNumber,
                    TableType = DiningTableManager.GeTableType(t.TableTypeId),
                    Name = t.Name
                }).ToList(),
                TableTypes = DiningTableManager.GetStoreDiningTableTypes(storeId)
            };
            return list;
        }

        /// <summary>
        /// 获取单个餐位信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DiningTableViewModel GetDiningTable(int id)
        {
            var t = DiningTableManager.GetDiningTable(id);
            return new DiningTableViewModel
            {
                DiningState = t.DiningState,
                Id = t.Id,
                StoreId = t.StoreId,
                TableNumber = t.TableNumber,
                TableType = DiningTableManager.GeTableType(t.TableTypeId),
                Name = t.Name,
                WeQrCode = t.WeQrCode
            };
        }
        /// <summary>
        /// 获取餐位类型设置
        /// </summary>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public IList<DiningTableType> GetDiningTableType(int storeId)
        {
            return DiningTableManager.GetStoreDiningTableTypes(storeId);
        }
        #endregion

        /// <summary>
        /// 通过文本获取语音播放地址
        /// </summary>
        /// <param name="startCode">前缀</param>
        /// <param name="lineNumber">编号</param>
        /// <returns></returns>
        private static string GetLineCodeVoiceSrc(string startCode, int lineNumber)
        {
            var str1 = lineNumber.ToString();
            if (lineNumber < 10)
                str1 = str1.PadLeft(2, '0');
            return string.IsNullOrEmpty(str1) ? string.Empty : $"http://static.711688.net.cn/voice/{startCode}{str1}.wav";
            
        }
    }
}